package com.shipwe.loans.ui.adapter

import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.recyclerview.widget.RecyclerView
import com.shipwe.adapter.ShipweRecyclerViewAdapter
import com.shipwe.adapter.ShipweViewHolderHelper
import com.shipwe.loans.R
import com.shipwe.loans.configs.ShipweConfigs
import com.shipwe.loans.utils.event.AppEventPointHelper
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import com.shipwe.loans.weight.input.CustomEditText
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/19 13:54
 * @Annotation：认证流程步骤适配器
 */
class AuthStepCommonAdapter(recyclerView: RecyclerView?): ShipweRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//出生日期选择
                return R.layout.auth_step_select_item
            }
            "GENDER_PICK" -> {//性别
                return R.layout.auth_step_gender_item
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.auth_step_mobile_item
            }
            "SELECT" -> {//选择
                return R.layout.auth_step_select_item
            }
            else -> {//输入框
                return R.layout.auth_step_input_item
            }
        }
    }

    override fun setItemChildListener(helper: ShipweViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.authStepSelect)//选择
        helper.setItemChildClickListener(R.id.authStepContactImage)//选择联系人
        helper.setItemChildClickListener(R.id.authStepMobile)
    }

    override fun fillData(helper: ShipweViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val authStepTitle = helper.getTextView(R.id.authStepTitle)
        var showTitle = model.optString("title")
        if (ShipweConfigs.isSwahili()){
            showTitle = model.optString("title_sw")
        }
        authStepTitle.text = findKeywordColor(Color.parseColor("#FFFF4D3E"),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showAuthStepSelectItemView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showAuthStepContactMobileItemView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showAuthStepSelectGenderItemView(helper,position,model)
            }
            else -> {//输入框
                showAuthStepInputItemView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showAuthStepInputItemView(helper: ShipweViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val authStepEdit = helper.getView<CustomEditText>(R.id.authStepEdit)
        var showHint = model.optString("hint")
        if (ShipweConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        authStepEdit.setHint(showHint)
        authStepEdit.setBackgroundResource(R.drawable.circle_fff6f6f6)
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            if (selectItem != null) {
                showText = selectItem.optString("title")
            }
        }
        authStepEdit.setText(showText)
        authStepEdit.setInputFocusChangeListener { v, remark ->
            AppEventPointHelper.appEventPointRequestAction(String.format(AppEventPointType.FORM.SHIPWE_FORM_STEP_INPUT_XX,model.optString("paramName")),remark)
        }

        authStepEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepEdit.clearFocus()
                true
            }
            false
        }
        authStepEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择性别
     */
    private fun showAuthStepSelectGenderItemView(helper: ShipweViewHolderHelper, position: Int, model: JSONObject){
        val genderMale = helper.getTextView(R.id.genderMale)
        genderMale.setTextColor(Color.parseColor("#FFB8B5B4"))
        genderMale.setBackgroundResource(R.drawable.circle_fff6f6f6)

        val genderFemale = helper.getTextView(R.id.genderFemale)
        genderFemale.setTextColor(Color.parseColor("#FFB8B5B4"))
        genderFemale.setBackgroundResource(R.drawable.circle_fff6f6f6)

        val values = model.optJSONArray("values")
        if (values != null){
            if (values.length() > 0){
                val item = values.optJSONObject(0)
                var showTitle = item.optString("title")
                if (ShipweConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                genderMale.text = showTitle
            }
            if (values.length() > 1){
                val item = values.optJSONObject(1)
                var showTitle = item.optString("title")
                if (ShipweConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                genderFemale.text = showTitle
            }
        }

        //选中
        if (model.has("selectItem")){
            val selectValue = model.getJSONObject("selectItem")
            if (values != null){
                if (values.length() > 0){
                    val item = values.optJSONObject(0)
                    if (item.optString("title") == selectValue.optString("title")){
                        genderMale.setTextColor(Color.parseColor("#FFFFFFFF"))
                        genderMale.setBackgroundResource(R.drawable.btn_circle_selector_ff7543ff)
                    }
                }
                if (values.length() > 1){
                    val item = values.optJSONObject(1)
                    if (item.optString("title") == selectValue.optString("title")){
                        genderFemale.setTextColor(Color.parseColor("#FFFFFFFF"))
                        genderFemale.setBackgroundResource(R.drawable.btn_circle_selector_ff7543ff)
                    }
                }
            }
        }

        genderMale.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(0)
                model.put("selectItem", item)
                AppEventPointHelper.appEventPointRequestAction(String.format(AppEventPointType.CLICK.SHIPWE_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }

        genderFemale.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(1)
                model.put("selectItem", item)
                AppEventPointHelper.appEventPointRequestAction(String.format(AppEventPointType.CLICK.SHIPWE_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }
    }

    /**
     * 选择类型
     */
    private fun showAuthStepSelectItemView(helper: ShipweViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (ShipweConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepSelectText = helper.getTextView(R.id.authStepSelectText)
        authStepSelectText.setHint(showHint)
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (ShipweConfigs.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            authStepSelectText.text = showTitle
        }

        val authStepSelectImage = helper.getImageView(R.id.authStepSelectImage)
        authStepSelectImage.setImageResource(R.drawable.down_black)
        when(model.optString("action")){
            "SELECT" ->{//选择
                authStepSelectImage.setImageResource(R.drawable.down_black)
            }
            "DATE_PICK" -> {//出生日期
                authStepSelectImage.setImageResource(R.drawable.down_black)
            }
        }
    }

    /**
     * 联系电话
     */
    private fun showAuthStepContactMobileItemView(helper: ShipweViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (ShipweConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepMobile = helper.getTextView(R.id.authStepMobile)
        authStepMobile.setHint(showHint)
        val authStepMobileEdit = helper.getView<EditText>(R.id.authStepMobileEdit)
        authStepMobileEdit.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            authStepMobile.text = showValue
            authStepMobileEdit.setText(showValue)
        }
        authStepMobileEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepMobileEdit.clearFocus()
                true
            }
            false
        }
        authStepMobileEdit.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                AppEventPointHelper.appEventPointRequestAction(String.format(AppEventPointType.FORM.SHIPWE_FORM_STEP_INPUT_XX,model.optString("paramName")),authStepMobileEdit.text.toString())
            }
        }
        authStepMobileEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isConfigAccount = ShipweSharedHelper.getShipweSharedBoolean(ShipweSharedKey.SHIPWE_IS_CONFIG_ACCOUNT)
        if(isConfigAccount){//审核账号 - 允许输入或选择
            authStepMobile.visibility = View.GONE
            authStepMobileEdit.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            authStepMobile.visibility = View.VISIBLE
            authStepMobileEdit.visibility = View.GONE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}